/**
 * 
 */
package com.jd.jdmvc.framework.template.viewrender;

import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jetbrick.template.JetContext;
import jetbrick.template.JetEngine;
import jetbrick.template.JetTemplate;
import jetbrick.template.ResourceNotFoundException;
import jetbrick.template.web.JetWebEngineLoader;
import com.alibaba.fastjson.JSONObject;
import com.jd.jdmvc.framework.template.context.JdMvcContext;
import com.jd.mvc.core.render.ViewRender;
import com.jd.mvc.core.util.MvcPageUtil;
/**
 * @author liubing1
 *
 */
public class JdMvcTemplateViewRender implements ViewRender {

	/* (non-Javadoc)
	 * @see com.jd.mvc.core.render.ViewRender#renderPage(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String)
	 */
	
	public void renderPage(HttpServletRequest request,
			HttpServletResponse response, String view) throws Exception {
		// TODO Auto-generated method stub
		if(view.contains(".jd")){//模板引擎
			JetEngine engine = JetWebEngineLoader.getJetEngine();
	        if (response.getContentType() == null) {
	            response.setContentType("text/html");
	        }
	        response.setCharacterEncoding(engine.getConfig().getOutputEncoding());
	        try {
	            JetTemplate template = engine.getTemplate(view);
	           // Map<String, Object> context=new HashMap<String, Object>();
	            JetContext context = new JdMvcContext(request, response);
	            // 创建 context 对象
	            template.render(context, response.getWriter());
	            
	        } catch (ResourceNotFoundException e) {
	            response.sendError(HttpServletResponse.SC_NOT_FOUND, "Template not found: " + view);
	        }
	        
		}else{
			MvcPageUtil.redirectPage(request, response, view, true);
		}
	}
	/* (non-Javadoc)
	 * @see com.jd.mvc.core.render.ViewRender#renderResult(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.String)
	 */
	public void renderResult(HttpServletRequest request,
			HttpServletResponse response, Object result, String returnType)
			throws Exception {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain");
		response.setContentType("text/html;charset=UTF-8");
		String jsonResult="";
		if(returnType.equalsIgnoreCase("JSON")){
			jsonResult=JSONObject.toJSONString(result);
		}else{
			jsonResult=result+"";
		}
		PrintWriter out =response.getWriter();
		out.print(jsonResult);
		
	}

	/* (non-Javadoc)
	 * @see com.jd.mvc.core.render.ViewRender#init(javax.servlet.ServletContext)
	 */
	public void init(ServletContext servletContext) {
		// TODO Auto-generated method stub
		JetWebEngineLoader.setServletContext(servletContext);
	}

}
